package com.example.item01.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.item01.proj.Result;
import com.example.item01.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j

public class LoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

        String url = req.getRequestURL().toString();
        if(url.contains("login")){//登录界面
            log.info("url是{}",url);

            return true;
        }
        String jwt = req.getHeader("token");

        if(!StringUtils.hasLength(jwt)){//空            为什么不直接length调用
            Result error = Result.error("NOT_LOGIN");
            log.info("jwt令牌为空,无效");
            String jsonString = JSONObject.toJSONString(error);
            res.getWriter().write(jsonString);
            return false;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析错误");
            Result error = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(error);
            res.getWriter().write(jsonString);
            return false;
        }
        log.info("令牌合法,放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("posthandle....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("aftercompletion....");
    }
}
